/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：默认的Xml函数集辅助模板
* CreateTime：2020-04-05 21:53:37
* Version：1.0
* Modify Recorder：
*************************************************/

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace TinyToolKit
{
    public class DefaultXmlTemplate : TinyUtility.XML.IXmlTemplate
    {
        public void XmlSerialize(string savePath, object obj)
        {
            string dirPath = Path.GetDirectoryName(savePath);
            if (string.IsNullOrEmpty(dirPath) == false && Directory.Exists(dirPath) == false)
                Directory.CreateDirectory(dirPath);
            
            //FileMode.Create 会覆盖已有的文件
            FileStream fileStream = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);

            XmlSerializer xml = new XmlSerializer(obj.GetType());
            xml.Serialize(streamWriter, obj);

            streamWriter.Close();
            fileStream.Close();
        }

        public T XmlDeSerialize<T>(string targetPath) where T : class
        {
            FileStream fs = new FileStream(targetPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            T obj = xmlSerializer.Deserialize(fs) as T; 
            fs.Close();

            return obj;
        }

        public object XmlDeSerialize(Type objectType, string targetPath)
        {
            FileStream fs = new FileStream(targetPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            XmlSerializer xmlSerializer = new XmlSerializer(objectType);
            object obj = xmlSerializer.Deserialize(fs);
            fs.Close();

            return obj;
        }
    }
}

